package org.cuatrovientos.signin;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author Dani
 * Servlet implementation class SignIn
 */
@WebServlet("/SignIn")
public class SignIn extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SignIn() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession();
		PrintWriter output = response.getWriter();

		String login = request.getParameter("login");
		String password = request.getParameter("password");

		Pattern patron = Pattern.compile("^[a-z]{4}$");
		Matcher comprobador = patron.matcher(login);
		
		if (comprobador.find()){
			if(login.equals("pepe") && password.equals("pepino")){
				session.setAttribute("login", login);
				this.getServletContext().getRequestDispatcher("/Private")
				.forward(request, response);
			}else{
				request.setAttribute("error", "Login incorrect");
				this.getServletContext().getRequestDispatcher("/login.jsp")
				.forward(request, response);
			}
		}else{
			request.setAttribute("loginerror", "The login is not correct");
			this.getServletContext().getRequestDispatcher("/login.jsp")
			.forward(request, response);
		}
	}

}
